package com.starrin.tennisfinder.system;

import com.starrin.tennisfinder.model.BookingStatus;
import com.starrin.tennisfinder.model.HourAvailability;
import com.starrin.tennisfinder.model.VenueAvailabilityDataHolder;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by larsstarrin on 03/02/14.
 */
public class Cache {

    private static Cache instance = null;

    protected Cache() {
        // Exists only to defeat instantiation.
    }

    public static Cache getInstance() {
        if (instance == null) {
            instance = new Cache();
        }
        return instance;
    }

    private final ConcurrentHashMap<String, Map<String, VenueAvailabilityDataHolder>> map = new ConcurrentHashMap<>();

    public Map<String, VenueAvailabilityDataHolder> getEntry(String key) {
        return map.get(key);
    }

    public VenueAvailabilityDataHolder getEntry(String date, String venueKey) {
        Map<String, VenueAvailabilityDataHolder> venueAvailabilityDataHolderMap = map.get(date);
        if (venueAvailabilityDataHolderMap == null) {
            return getUnavailableDataHolder();
        }
        if(venueAvailabilityDataHolderMap.get(venueKey) == null) {
            return getUnavailableDataHolder();
        }
        return venueAvailabilityDataHolderMap.get(venueKey);
    }

    private VenueAvailabilityDataHolder getUnavailableDataHolder() {
        VenueAvailabilityDataHolder holder = new VenueAvailabilityDataHolder();
        for (int i = 7; i < 23; i++) {
            holder.addAvailability(new HourAvailability(1, BookingStatus.NA, null));
        }
        return holder;
    }

    public void putEntry(String date, String venueKey, VenueAvailabilityDataHolder dataHolder) {
        Map<String, VenueAvailabilityDataHolder> holderByDate = map.get(date);
        if(holderByDate == null) {
            holderByDate = new ConcurrentHashMap<>();
        }
        holderByDate.put(venueKey, dataHolder);
        map.put(date, holderByDate);
    }
}


